# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.


# def print_hi(name):
# Use a breakpoint in the code line below to debug your script.
# print(f'Hi, {name}')  # Press Ctrl+F8 to toggle the breakpoint.


# Press the green button in the gutter to run the script.
# if __name__ == '__main__':
#     print_hi('PyCharm')

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
from lxml import etree
from utils import Utils
import requests
import re


class YouDian(object):
    def __init__(self):
        self.encoding = 'utf8'
        self.url = "http://ivi.bupt.edu.cn/"  # 北京邮电大学（官方)地址
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36"
        }
        self.session = requests.session()

    def __get_data(self):
        request = self.session.get(self.url, headers=self.headers)
        request.encoding = self.encoding
        return request.text

    def __parse_data(self, html_data):
        data = []
        html = etree.HTML(html_data)
        result = html.xpath("//div[@style='margin-top:50px']/div")
        for item in result:
            zhiboyuan = {
                "url": self.url + item.xpath("./a/@href")[0],
                "name": item.xpath("./p/text()")[0]
            }
            data.append(zhiboyuan)
        return data

    def __get_live_source(self, data):
        if data:
            live_sources = []
            for item in data:
                # http://ivi.bupt.edu.cn/hls/cctv1hd.m3u8
                channel = self.get_channel_from_url(item['url'])
                if channel:
                    live_source = {
                        'url': self.url + '/hls/' + channel + '.m3u8',
                        'name': item['name'].replace('-', '').replace(' ', '').upper()
                    }
                    live_sources.append(live_source)
            return live_sources

    def get_channel_from_url(self, url):
        pattern = re.compile('channel=(.+)')
        result = re.search(pattern, url).groups()[0]
        return result

    def get_live_sources(self):
        text = self.__get_data()
        data = self.__parse_data(text)
        return self.__get_live_source(data)

    def test_valid(self, url):
        request = self.session.get(url)
        return request.status_code == 200

    def run(self):
        text = self.__get_data()
        data = self.__parse_data(text)
        Utils.write_file(self.__get_live_source(data))

def test(self):
    request = self.session.get("https://cctvalih5ca.v.myalicdn.com/live/cctv1_2/index.m3u8")
    print(request.status_code)


if __name__ == '__main__':
    zhi = YouDian()
    zhi.run()
    # 'cctv3', '海南卫视', 'cctv12', 'cctv14', '湖南卫视', '广东卫视', '广西卫视'
    # student = [['Tom', 'A', 20], ['Jack', 'C', 18], ['Andy', 'B', 11]]
    # student.sort(key=lambda student: student[2])
    # print(student)
